import os
import cv2 as cv
from PIL import Image
import numpy as np

def getImageAndLabels(path):
    facesSamples = []
    ids = []
    imagePaths = [os.path.join(path,f) for f in os.listdir(path)]   # 路径
    face_detector = cv.CascadeClassifier(cv.data.haarcascades+'haarcascade_frontalface_alt2.xml')   # 检测人脸
    for imagePath in imagePaths:
        PIL_img = Image.open(imagePath).convert('L')    # 打开图片，并且黑白化
        img_numpy = np.array(PIL_img,'uint8')   # 将图像变为数组，以黑白深浅
        faces = face_detector.detectMultiScale(img_numpy)   # 获取特征
        id = int(os.path.split(imagePath)[1].split('.')[0])     # 图片序号
        for x,y,w,h in faces:
            ids.append(id)
            facesSamples.append(img_numpy[y:y+h,x:x+w])

    print('id:',id) # 打印序号
    print('fs:',facesSamples)   # 打印训练数组
    return facesSamples,ids     #返回序号组和训练数组

def train():
    path = './jm/'     # 图片路径
    faces , ids = getImageAndLabels(path)   # 获取序号数组和训练数组
    recognizer = cv.face.LBPHFaceRecognizer_create()    # 获取训练对象
    recognizer.train(faces,np.array(ids))   # 开始训练
    recognizer.write('./trainer/trainer.yml')      # 训练数据放入指定路径